import { useState, useEffect, useCallback } from 'react';
import { ServerMetric, Task, Alert, SystemStatus } from '../types';
import {
  generateInitialData,
  updateServerMetrics,
  updateTasks,
  calculateSystemStatus
} from '../utils/dataGenerator';

interface UseDataStreamReturn {
  isRunning: boolean;
  servers: ServerMetric[];
  tasks: Task[];
  alerts: Alert[];
  systemStatus: SystemStatus;
  searchTerm: string;
  toggleDataStream: () => void;
  refreshData: () => void;
  setSearchTerm: (term: string) => void;
}

export const useDataStream = (): UseDataStreamReturn => {
  const [isRunning, setIsRunning] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [servers, setServers] = useState<ServerMetric[]>([]);
  const [tasks, setTasks] = useState<Task[]>([]);
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [systemStatus, setSystemStatus] = useState<SystemStatus>({
    totalServers: 0,
    healthyServers: 0,
    warningServers: 0,
    criticalServers: 0,
    avgCpu: 0,
    avgMemory: 0,
    avgLoad: 0,
    networkBalance: 'balanced',
    networkRatio: 1
  });

  const updateData = useCallback(() => {
    setServers(prev => updateServerMetrics(prev));
    setTasks(prev => updateTasks(prev));
  }, []);

  const refreshData = useCallback(() => {
    const { servers: newServers, tasks: newTasks, alerts: newAlerts } = generateInitialData();
    setServers(newServers);
    setTasks(newTasks);
    setAlerts(newAlerts);
  }, []);

  const toggleDataStream = useCallback(() => {
    setIsRunning(prev => !prev);
  }, []);

  useEffect(() => {
    const { servers: initialServers, tasks: initialTasks, alerts: initialAlerts } = generateInitialData();
    setServers(initialServers);
    setTasks(initialTasks);
    setAlerts(initialAlerts);
  }, []);

  useEffect(() => {
    const status = calculateSystemStatus(servers);
    setSystemStatus(status);
  }, [servers]);

  useEffect(() => {
    let interval: number;

    if (isRunning) {
      interval = window.setInterval(updateData, 1500);
    }

    return () => {
      if (interval) {
        window.clearInterval(interval);
      }
    };
  }, [isRunning, updateData]);

  return {
    isRunning,
    servers,
    tasks,
    alerts,
    systemStatus,
    searchTerm,
    toggleDataStream,
    refreshData,
    setSearchTerm
  };
};